import { Injectable } from '@nestjs/common';
import { Server } from 'socket.io';
import { CreateChatgptDto } from './dto/create-chatgpt.dto';
import { UpdateChatgptDto } from './dto/update-chatgpt.dto';
import OpenAI from "openai";
import { v4 as uuidv4 } from 'uuid';

@Injectable()
export class ChatgptService {
  private abortControllers: Map<string, AbortController> = new Map();

  async handleChat(server: Server, createChatgptDto: CreateChatgptDto) {
    console.log('Received message:', createChatgptDto);

    const openai = new OpenAI({
      baseURL: 'https://api.deepseek.com',
      apiKey: 'sk-d25eda73da4c4d548739a958c33e6aab'
    });

    // 构建消息数组
    const messages = createChatgptDto.message.map(item => ({
      role: item.name === 'AI' ? 'assistant' as const : 'user' as const,
      content: item.message
    }));

    // 生成唯一的会话ID
    const conversationId = uuidv4();
    
    // 创建AbortController用于中断流
    const controller = new AbortController();
    this.abortControllers.set(conversationId, controller);

    try {
      // 发送连接建立事件
      server.emit('message', { type: 'connected', message: '连接已建立' });

      const stream = await openai.chat.completions.create({
        model: 'deepseek-chat',
        messages: messages,
        stream: true,
        temperature: 0.7,
        max_tokens: 1000
      }, {
        signal: controller.signal // 将AbortController的signal传递给OpenAI
      });

      let fullResponse = '';

      // 监听流式数据的每个块
      for await (const chunk of stream) {
        const content = chunk.choices[0]?.delta?.content;
        if (content) {
          fullResponse += content;

          // 使用WebSocket发送数据
          const wsData = {
            conversationId: conversationId,
            type: 'content',
            content: content,
            timestamp: new Date().toISOString()
          };

          server.emit('chatContent', wsData);
        }
      }

      // 发送完成事件
      server.emit('chatDone', {
        type: 'done',
        message: '对话完成',
        fullResponse: fullResponse,
        conversationId: conversationId
      });

      // 清理AbortController
      this.abortControllers.delete(conversationId);

    } catch (error) {
      console.error('ChatGPT API Error:', error);

      // 如果是中断错误，发送中断完成事件
      if (error.name === 'AbortError') {
        server.emit('generationStopped', { 
          success: true, 
          conversationId: conversationId,
          message: '生成已中断'
        });
      } else {
        // 发送错误事件
        const errorData = {
          type: 'error',
          message: 'AI服务暂时不可用',
          error: error.message,
          conversationId: conversationId
        };
        server.emit('chatError', errorData);
      }

      // 清理AbortController
      this.abortControllers.delete(conversationId);
    }
  }

  stopGeneration(server: Server, conversationId: string) {
    console.log('Attempting to stop generation for conversationId:', conversationId);
    console.log('Available controllers:', Array.from(this.abortControllers.keys()));

    const controller = this.abortControllers.get(conversationId);
    console.log('Found controller:', controller);

    if (controller) {
      try {
        controller.abort();
        this.abortControllers.delete(conversationId);
        console.log('Generation stopped successfully for conversationId:', conversationId);
        
        server.emit('generationStopped', { 
          success: true, 
          conversationId: conversationId,
          message: '生成已中断'
        });
      } catch (error) {
        console.error('Error stopping generation:', error);
        server.emit('generationStopped', { 
          success: false, 
          conversationId: conversationId,
          message: '中断失败'
        });
      }
    } else {
      console.log('No controller found for conversationId:', conversationId);
      server.emit('generationStopped', { 
        success: false, 
        conversationId: conversationId,
        message: '未找到对应的会话'
      });
    }
  }
}
